package org.btik.lightweb.client.login;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Random;

/**
 * @author lustre
 * @since 2023/6/11 12:17
 */
public class CaptchaGenerator {

    //使用到Algerian字体，系统里没有的话需要安装字体，字体只显示大写，去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final Random random = new Random();

    private static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     *
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 输出指定验证码图片流
     *
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        //绘制干扰线
        SecureRandom random = new SecureRandom();
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(225, 255);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h - 4);

        //shear(g2, w, h, c);// 使图片扭曲


        Color yawp = getRandColor(90, 180);
        // 添加噪点
        int area = w * h;
        int randomPosStep = random.nextInt(10);
        randomPosStep += 10;
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            if ((x + y) % randomPosStep == 0) {
                yawp = getRandColor(90, 180);
            }
            image.setRGB(x, y, yawp.getRGB());
        }


        Color textColor = getRandColor(80, 150);
        g2.setColor(textColor);

        char[] chars = code.toCharArray();
        int fontSize = h * 85 / 100;
        for (int i = 0; i < verifySize; i++) {

            Font font = new Font("Algerian", Font.ITALIC, fontSize);
            g2.setFont(font);

            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 5 * random.nextDouble() * (random.nextBoolean() ? 1 : -1), ((double) w / verifySize) * i + (double) fontSize / 2, (double) h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, (int) (((w * 0.9) / verifySize) * i + 5), h / 2 + fontSize / 2 - 10);
        }
        //g2.setColor(getRandColor(100, 200));// 设置线条的颜色
        g2.setStroke(new BasicStroke(4));
        g2.getTransform().setToRotation(-1);
        for (int i = 0; i < 30; i++) {
            int x = random.nextInt(w);
            int y = h * (3 + random.nextInt(6)) / 10;
            int xl = random.nextInt(w);
            g2.drawLine(x, y, xl, y);
        }

        g2.dispose();
        ImageIO.write(image, "png", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

}
